package com.xm.transfer.servlet;

import com.xm.transfer.annotations.Autowired;
import com.xm.transfer.factory.BeanFactory;
import com.xm.transfer.service.TransferService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

@WebServlet(name = "transferServlet", urlPatterns = "/transferServlet")
public class TransferServlet extends HttpServlet {

//    private TransferService transferService = ((ProxyFactory)BeanFactory.getBean(ProxyFactory.class)).getJDKProxy(BeanFactory.getBean(TransferService.class));
    @Autowired
    private TransferService transferService;

    @Override
    public void init() throws ServletException {
        Field[] declaredFields = this.getClass().getDeclaredFields();
        for (int i = 0; i < declaredFields.length; i++) {
            Field declaredField = declaredFields[i];
            Annotation[] annotations = declaredField.getAnnotations();
            for (int j = 0; j < annotations.length; j++) {
                Annotation annotation = annotations[j];
                if (annotation instanceof Autowired) {
                    declaredField.setAccessible(true);
                    try {
                        declaredField.set(this, BeanFactory.getBean(declaredField.getType().getSimpleName()));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        String money = req.getParameter("money");
        System.out.println("进入了" + fromCardNo + ":" + toCardNo + ":" + money);
        try {
            transferService.transfer(fromCardNo, toCardNo, Double.parseDouble(money));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
